'use client'

import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { Trash2, Edit3, Check, X, GripVertical, Shield } from 'lucide-react'
import { 
  Todo, 
  TodoStatus, 
  TodoPriority,
  STATUS_LABELS,
  PRIORITY_LABELS,
  STATUS_COLORS,
  PRIORITY_COLORS 
} from '../types/todo'

interface SortableTodoItemProps {
  todo: Todo
  isEditing: boolean
  editingData: Partial<Todo>
  onStartEdit: (todo: Todo) => void
  onSaveEdit: () => void
  onCancelEdit: () => void
  onToggleComplete: (todo: Todo) => void
  onDelete: (id: number) => void
  onEditingDataChange: (data: Partial<Todo>) => void
  onEditKeyPress: (e: React.KeyboardEvent) => void
}

export default function SortableTodoItem({
  todo,
  isEditing,
  editingData,
  onStartEdit,
  onSaveEdit,
  onCancelEdit,
  onToggleComplete,
  onDelete,
  onEditingDataChange,
  onEditKeyPress
}: SortableTodoItemProps) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: todo.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`p-4 bg-white hover:bg-gray-50 transition-colors duration-150 border-b border-gray-200 ${
        todo.status === TodoStatus.COMPLETED ? 'bg-green-50' : ''
      } ${
        isDragging ? 'shadow-lg z-50' : ''
      }`}
    >
      <div className="flex items-start gap-3">
        <button
          {...attributes}
          {...listeners}
          className="mt-1 p-1 text-gray-400 hover:text-gray-600 cursor-grab active:cursor-grabbing transition-colors"
          title="拖拽排序"
        >
          <GripVertical size={16} />
        </button>

        <button
          onClick={() => onToggleComplete(todo)}
          className={`mt-1 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors duration-200 ${
            todo.status === TodoStatus.COMPLETED
              ? 'bg-green-500 border-green-500 text-white'
              : 'border-gray-300 hover:border-green-400'
          }`}
        >
          {todo.status === TodoStatus.COMPLETED && <Check size={14} />}
        </button>

        <div className="flex-1 min-w-0">
          {isEditing ? (
            <div className="space-y-3">
              <input
                type="text"
                value={editingData.title || ''}
                onChange={(e) => onEditingDataChange({ ...editingData, title: e.target.value })}
                onKeyPress={onEditKeyPress}
                className="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                autoFocus
              />
              <textarea
                value={editingData.description || ''}
                onChange={(e) => onEditingDataChange({ ...editingData, description: e.target.value })}
                placeholder="任务描述（可选）..."
                rows={2}
                className="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
              />
              <div className="flex gap-4">
                <select
                  value={editingData.status || TodoStatus.PENDING}
                  onChange={(e) => onEditingDataChange({ ...editingData, status: e.target.value as TodoStatus })}
                  className="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value={TodoStatus.PENDING}>待处理</option>
                  <option value={TodoStatus.IN_PROGRESS}>进行中</option>
                  <option value={TodoStatus.COMPLETED}>已完成</option>
                </select>
                <select
                  value={editingData.priority || TodoPriority.MEDIUM}
                  onChange={(e) => onEditingDataChange({ ...editingData, priority: e.target.value as TodoPriority })}
                  className="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value={TodoPriority.LOW}>低优先级</option>
                  <option value={TodoPriority.MEDIUM}>中优先级</option>
                  <option value={TodoPriority.HIGH}>高优先级</option>
                </select>
              </div>
            </div>
          ) : (
            <div>
              <div className="flex items-center gap-2 mb-1">
                <span
                  className={`font-medium ${
                    todo.status === TodoStatus.COMPLETED
                      ? 'line-through text-gray-500'
                      : 'text-gray-800'
                  }`}
                >
                  {todo.title}
                </span>
                {/* 管理员分配标识 */}
                {todo.assigned_by_admin && (
                  <div title="管理员分配的任务" className="inline-flex">
                    <Shield 
                      size={14} 
                      className="text-blue-500" 
                    />
                  </div>
                )}
                <span className={`px-2 py-1 rounded-full text-xs font-medium ${STATUS_COLORS[todo.status]}`}>
                  {STATUS_LABELS[todo.status]}
                </span>
                <span className={`px-2 py-1 rounded-full text-xs font-medium ${PRIORITY_COLORS[todo.priority]}`}>
                  {PRIORITY_LABELS[todo.priority]}
                </span>
              </div>
              {todo.description && (
                <p className={`text-sm mb-2 ${
                  todo.status === TodoStatus.COMPLETED
                    ? 'text-gray-400'
                    : 'text-gray-600'
                }`}>
                  {todo.description}
                </p>
              )}
              <div className="text-xs text-gray-400">
                创建于: {new Date(todo.created_at).toLocaleString('zh-CN')}
                {todo.updated_at !== todo.created_at && (
                  <span className="ml-2">
                    更新于: {new Date(todo.updated_at).toLocaleString('zh-CN')}
                  </span>
                )}
              </div>
            </div>
          )}
        </div>

        <div className="flex gap-2 mt-1">
          {isEditing ? (
            <>
              <button
                onClick={onSaveEdit}
                disabled={!editingData.title?.trim()}
                className="p-2 text-green-600 hover:bg-green-100 rounded transition-colors duration-200 disabled:text-gray-400 disabled:hover:bg-transparent"
                title="保存"
              >
                <Check size={18} />
              </button>
              <button
                onClick={onCancelEdit}
                className="p-2 text-gray-600 hover:bg-gray-100 rounded transition-colors duration-200"
                title="取消"
              >
                <X size={18} />
              </button>
            </>
          ) : (
            <>
              <button
                onClick={() => onStartEdit(todo)}
                className="p-2 text-blue-600 hover:bg-blue-100 rounded transition-colors duration-200"
                title="编辑"
              >
                <Edit3 size={18} />
              </button>
              {/* 只有非管理员分配的任务才显示删除按钮 */}
              {!todo.assigned_by_admin && (
                <button
                  onClick={() => onDelete(todo.id)}
                  className="p-2 text-red-600 hover:bg-red-100 rounded transition-colors duration-200"
                  title="删除"
                >
                  <Trash2 size={18} />
                </button>
              )}
              {/* 管理员分配的任务显示提示信息 */}
              {todo.assigned_by_admin && (
                <div 
                  className="p-2 text-gray-400 cursor-not-allowed" 
                  title="管理员分配的任务，不能删除"
                >
                  <Trash2 size={18} className="opacity-30" />
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}